package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.entity.MesEmployeeWorkType;
import org.jeecg.modules.mes.mapper.MesEmployeeWorkTypeMapper;
import org.jeecg.modules.mes.service.IMesEmployeeWorkTypeService;
import org.jeecg.modules.mes.vo.MesEmployeeWorkTypeAssignVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 员工工种关联表 Service 实现类
 */
@Slf4j
@Service
public class MesEmployeeWorkTypeServiceImpl extends ServiceImpl<MesEmployeeWorkTypeMapper, MesEmployeeWorkType> implements IMesEmployeeWorkTypeService {

    @Autowired
    private MesEmployeeWorkTypeMapper employeeWorkTypeMapper;

    @Override
    public IPage<MesEmployeeWorkType> queryPageList(Page<MesEmployeeWorkType> page, Map<String, Object> params) {
        return employeeWorkTypeMapper.queryPageList(page, params);
    }

    @Override
    public List<MesEmployeeWorkType> getEmployeeWorkTypes(String employeeId) {
        if (StringUtils.isBlank(employeeId)) {
            return null;
        }
        return employeeWorkTypeMapper.selectByEmployeeId(employeeId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> assignWorkTypeToEmployee(MesEmployeeWorkTypeAssignVO assignVO) {
        try {
            if (assignVO == null || StringUtils.isBlank(assignVO.getEmployeeId()) || 
                assignVO.getWorkTypes() == null || assignVO.getWorkTypes().isEmpty()) {
                return Result.error("参数不能为空");
            }

            // 先删除该员工的所有工种分配
            QueryWrapper<MesEmployeeWorkType> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("employee_id", assignVO.getEmployeeId());
            this.remove(deleteWrapper);

            // 重新分配工种
            for (MesEmployeeWorkTypeAssignVO.WorkTypeAssignItem item : assignVO.getWorkTypes()) {
                MesEmployeeWorkType employeeWorkType = new MesEmployeeWorkType();
                employeeWorkType.setEmployeeId(assignVO.getEmployeeId());
                employeeWorkType.setEmployeeName(assignVO.getEmployeeName());
                employeeWorkType.setWorkTypeId(item.getWorkTypeId());
                employeeWorkType.setWorkTypeCode(item.getWorkTypeCode());
                employeeWorkType.setWorkTypeName(item.getWorkTypeName());
                employeeWorkType.setSkillLevel(item.getSkillLevel());
                employeeWorkType.setCertifier(item.getCertifier());
                employeeWorkType.setStatus(1); // 启用状态
                employeeWorkType.setCertificationDate(new Date());

                this.save(employeeWorkType);
            }

            return Result.OK("员工工种分配成功");
        } catch (Exception e) {
            log.error("员工工种分配失败", e);
            return Result.error("员工工种分配失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<MesEmployeeWorkType> saveEmployeeWorkType(MesEmployeeWorkType employeeWorkType) {
        try {
            // 检查是否已存在相同的员工工种分配
            if (checkEmployeeWorkTypeExists(employeeWorkType.getEmployeeId(), 
                                          employeeWorkType.getWorkTypeId(), null)) {
                return Result.error("该员工已分配此工种，请勿重复分配");
            }

            employeeWorkType.setCreateTime(new Date());

            // 设置默认值
            if (employeeWorkType.getStatus() == null) {
                employeeWorkType.setStatus(1);
            }
            if (employeeWorkType.getSkillLevel() == null) {
                employeeWorkType.setSkillLevel(1);
            }
            if (employeeWorkType.getCertificationDate() == null) {
                employeeWorkType.setCertificationDate(new Date());
            }

            this.save(employeeWorkType);

            return Result.OK("员工工种分配添加成功", employeeWorkType);
        } catch (Exception e) {
            log.error("保存员工工种分配失败", e);
            return Result.error("保存员工工种分配失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<MesEmployeeWorkType> updateEmployeeWorkType(MesEmployeeWorkType employeeWorkType) {
        try {
            // 检查是否已存在相同的员工工种分配（排除当前记录）
            if (checkEmployeeWorkTypeExists(employeeWorkType.getEmployeeId(), 
                                          employeeWorkType.getWorkTypeId(), employeeWorkType.getId())) {
                return Result.error("该员工已分配此工种，请勿重复分配");
            }

            // 获取当前用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            employeeWorkType.setUpdateBy(sysUser.getUsername());
            employeeWorkType.setUpdateTime(new Date());

            this.updateById(employeeWorkType);

            return Result.OK("员工工种分配更新成功", employeeWorkType);
        } catch (Exception e) {
            log.error("更新员工工种分配失败", e);
            return Result.error("更新员工工种分配失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> removeEmployeeWorkType(String id) {
        try {
            MesEmployeeWorkType employeeWorkType = this.getById(id);
            if (employeeWorkType == null) {
                return Result.error("员工工种分配不存在");
            }

            this.removeById(id);

            return Result.OK("员工工种分配删除成功");
        } catch (Exception e) {
            log.error("删除员工工种分配失败", e);
            return Result.error("删除员工工种分配失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> removeEmployeeWorkTypes(List<String> ids) {
        try {
            this.removeByIds(ids);
            return Result.OK("批量删除员工工种分配成功");
        } catch (Exception e) {
            log.error("批量删除员工工种分配失败", e);
            return Result.error("批量删除员工工种分配失败：" + e.getMessage());
        }
    }

    @Override
    public boolean checkEmployeeWorkTypeExists(String employeeId, String workTypeId, String excludeId) {
        if (StringUtils.isBlank(employeeId) || StringUtils.isBlank(workTypeId)) {
            return false;
        }

        int count = employeeWorkTypeMapper.checkEmployeeWorkTypeExists(employeeId, workTypeId, excludeId);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByWorkTypeId(String workTypeId) {
        if (StringUtils.isNotBlank(workTypeId)) {
            employeeWorkTypeMapper.deleteBatchByWorkTypeId(workTypeId);
        }
    }
}
